package com.rzico.order.receiver;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rzico.account.model.Attach;
import com.rzico.annotation.Log;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.order.entity.Order;
import com.rzico.order.enumx.OrderShippingStatusEnum;
import com.rzico.order.enumx.OrderStatusEnum;
import com.rzico.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.UUID;

/**
 * Created by icssh on 2020/1/28.
 */
@Controller
@Slf4j
public class PaymentReceiver implements ChannelAwareMessageListener {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OrderService orderService;


    @Autowired
    private EnterpriseService enterpriseService;


    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    @RabbitHandler
    @RabbitListener(queues = "queue.order.payment")
    public void onMessage(Message message, Channel channel) throws Exception {
        boolean success = false;
        try {

            //同一时刻服务器只会发送一条消息给消费者
            channel.basicQos(1);

            String str = new String(message.getBody());
            Attach attachQueue = JSON.parseObject(str,Attach.class);
            try {
                if ("0000".equals(attachQueue.getCode())) {
                    orderService.paymentHandle(Long.valueOf(attachQueue.getId()));

                    Order order = orderService.selectByPrimaryKey(Long.valueOf(attachQueue.getId()));
                    if (order.getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_CONFIRM.getId()) && order.getShippingStatus().equals(OrderShippingStatusEnum.SHIPPING_STATUS_UNSHIPPNG.getId())) {

                        Enterprise enterprise = enterpriseService.selectByPrimaryKey(order.getEnterpriseId());

                        if (enterprise.getShippingMethod().equals(1) && order.getOrderMethod().equals(0)) {
                            attachQueue = new Attach();
                            attachQueue.setId(String.valueOf(order.getId()));
                            attachQueue.setQueue("queue.order.shipping");
                            attachQueue.setCode("0000");
                            attachQueue.setDescription("自动接单");
                            Message mmessage = MessageBuilder
                                    .withBody(JSON.toJSONString(attachQueue).getBytes())
                                    .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                                    .build();
                            CorrelationData correlationData = new CorrelationData();
                            correlationData.setId(UUID.randomUUID().toString());
                            rabbitTemplate.convertAndSend("directExchange", attachQueue.getQueue() + ".key", mmessage, correlationData);
                        }
                    }

                }
                success = true;
            } catch (Exception e) {
                logger.error(str);
                logger.error(e.getMessage());
                success = false;
            }

        } finally {
            if (success) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }

}
